//
//  SISSChatViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/15.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSChatViewController.h"
#import "SISSChatBusinessCardCell.h"
#import "SISSChatRecommendCell.h"
#import "SISSNetworkingManager+Mine.h"
#import "SISSMessageRecommendViewController.h"
#import "SISSNavigationController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "SISSTabBarController.h"
#import "SISSInfomationViewController.h"

@interface SISSChatViewController ()<EaseMessageViewControllerDelegate,EaseMessageViewControllerDataSource,EaseMessageCellDelegate>

/* 个人信息 */
@property (strong, nonatomic) SISSPersonInfoModel *personInfo;


@end

@implementation SISSChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.backgroundColor = COLOR(0xF9F9F9);
    
    // 获取当前用户信息
    [self requestPeronInfo];
    
    // 只有中介才有右上角的查看资料
    self.navigationItem.rightBarButtonItem = self.contactModel.accountType == 1 ? [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"咨询_个人资料"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClickAction)] : nil;
    
    for (NSInteger i = 0; i <= 5; i++) {
        [self.chatBarMoreView removeItematIndex:i];
    }
//    [[EaseBaseMessageCell appearance] setAvatarSize:40.f];//设置头像大小
//    [[EaseBaseMessageCell appearance] setAvatarCornerRadius:20.f];//设置头像圆角
    
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;

//    [[EaseMessageCell appearance] setMessageTextFont:[UIFont systemFontOfSize:15]];//消息显示字体
    
//    [EaseBaseMessageCell appearance].sendMessageVoiceAnimationImages = 
//    [EaseBaseMessageCell appearance].recvMessageVoiceAnimationImages = 
    [EaseBaseMessageCell appearance].bubbleMaxWidth = 250;
    
    NSArray *imageNameArr = @[@"拍照", @"照片", @"名片", @"推荐"];
    for (NSInteger i = 0; i < imageNameArr.count; i++) {
        UIImage *image = [UIImage imageNamed:imageNameArr[i]];

        if (i > 1) {
            [self.chatBarMoreView insertItemWithImage:image highlightedImage:image title:imageNameArr[i]];
        } else {
            [self.chatBarMoreView updateItemWithImage:image highlightedImage:image title:imageNameArr[i] atIndex:i];
        }
    }
}

#pragma mark - 右上角个人资料按钮点击事件
- (void)rightBarButtonItemClickAction {
    
    NSLog(@"右上角查看详细信息");
    
    [kNetworkManager requestPersonInfoWithSpId:self.contactModel.spId success:^(SISSPersonInfoModel *personInfo) {
        
        SISSInfomationViewController *vc = [[UIStoryboard storyboardWithName:@"Mine" bundle:nil] instantiateViewControllerWithIdentifier:@"SISSInfomationViewController"];
        vc.personInfo = personInfo;
        
        vc.spId = self.contactModel.spId;
        [self.navigationController pushViewController:vc animated:YES];
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
    
//    [self presentViewController:vc animated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
//    SISSTabBarController *tabbar = (SISSTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//    tabbar.customTabBar.hidden = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
//    SISSTabBarController *tabbar = (SISSTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//    tabbar.customTabBar.hidden = NO;
}

#pragma mark - EaseMessageViewControllerDelegate &&EaseMessageViewControllerDataSource
- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController modelForMessage:(EMMessage *)message {
    //用户可以根据自己的用户体系，根据message设置用户昵称和头像
    id<IMessageModel> model = nil;
    model = [[EaseMessageModel alloc] initWithMessage:message];
    
    if (message.direction == EMMessageDirectionSend) {
        model.avatarImage = [UIImage imageNamed:@"头像"];//默认头像
        model.avatarURLPath = [SISSUserAccount shared].portrait;//头像网络地址
        model.nickname = @"";//用户昵称
    } else {
        model.avatarImage = [UIImage imageNamed:@"头像"];//默认头像
        model.avatarURLPath = self.contactModel.portrait;//头像网络地址
        model.nickname = @"";//用户昵称
    }
    
    return model;
}

- (UITableViewCell *)messageViewController:(UITableView *)tableView cellForMessageModel:(id<IMessageModel>)messageModel {
    
    [EaseBaseMessageCell appearance].messageVoiceDurationColor = messageModel.isSender ? [UIColor whiteColor] : COLOR(0x8998A5);
    [[EaseMessageCell appearance] setMessageTextColor:messageModel.isSender ? [UIColor whiteColor] : COLOR(0x334A60)]; // 消息显示颜色
    if (messageModel.bodyType == EMMessageBodyTypeImage) { // 图片不设置发送气泡
        [[EaseBaseMessageCell appearance] setSendBubbleBackgroundImage:[[UIImage imageNamed:@""] stretchableImageWithLeftCapWidth:5 topCapHeight:30]]; // 设置发送气泡
        [[EaseBaseMessageCell appearance] setRecvBubbleBackgroundImage:[[UIImage imageNamed:@""] stretchableImageWithLeftCapWidth:30 topCapHeight:30]]; // 设置接收气泡
    } else {
        
        [[EaseBaseMessageCell appearance] setSendBubbleBackgroundImage:[[UIImage imageNamed:@"chat_sender_bg"] stretchableImageWithLeftCapWidth:5 topCapHeight:30]]; // 设置发送气泡
        [[EaseBaseMessageCell appearance] setRecvBubbleBackgroundImage:[[UIImage imageNamed:@"chat_receiver_bg"] stretchableImageWithLeftCapWidth:30 topCapHeight:30]]; // 设置接收气泡
    }
    
    NSDictionary *dict = messageModel.message.ext;
    if (messageModel.bodyType == EMMessageBodyTypeText &&
        [dict[@"recommendType"] integerValue] == 3) {
        NSString *CellIdentifier = [SISSChatBusinessCardCell cellIdentifierWithModel:messageModel];
        SISSChatBusinessCardCell *cell = (SISSChatBusinessCardCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[SISSChatBusinessCardCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier model:messageModel];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.delegate = self;
        cell.model = messageModel;
        return cell;
    } else if (messageModel.bodyType == EMMessageBodyTypeText &&
                 ([dict[@"recommendType"] integerValue] == 1 || [dict[@"recommendType"] integerValue] == 2 || [dict[@"recommendType"] integerValue] == 4 || [dict[@"recommendType"] integerValue] == 5)) {
        NSString *CellIdentifier = [SISSChatRecommendCell cellIdentifierWithModel:messageModel];
        SISSChatRecommendCell *cell = (SISSChatRecommendCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[SISSChatRecommendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier model:messageModel];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.delegate = self;
        cell.model = messageModel;
        return cell;
    }
    return nil;
}

- (CGFloat)messageViewController:(EaseMessageViewController *)viewController
           heightForMessageModel:(id<IMessageModel>)messageModel
                   withCellWidth:(CGFloat)cellWidth{
    NSDictionary *dict = messageModel.message.ext;
    //样例为如果消息是文本消息使用用户自定义cell的高度
    if (messageModel.bodyType == EMMessageBodyTypeText &&
        [dict[@"recommendType"] integerValue] == 3) {
        //CustomMessageCell为用户自定义cell,继承了EaseBaseMessageCell

        return [SISSChatBusinessCardCell cellHeightWithModel:messageModel];
        
    } else if (messageModel.bodyType == EMMessageBodyTypeText &&
               ([dict[@"recommendType"] integerValue] == 1 || [dict[@"recommendType"] integerValue] == 2 || [dict[@"recommendType"] integerValue] == 4 || [dict[@"recommendType"] integerValue] == 5)) {
        //CustomMessageCell为用户自定义cell,继承了EaseBaseMessageCell
        return [SISSChatRecommendCell cellHeightWithModel:messageModel];
    }
    
    return 0.f;
}
#pragma mark - EaseMessageCellDelegate - 点击名片拨打电话
- (void)messageCellSelected:(id<IMessageModel>)model {
    
    NSDictionary *dict = model.message.ext;
    if (model.bodyType == EMMessageBodyTypeText &&
        [dict[@"recommendType"] integerValue] == 3) {
        // 点击名片
        NSLog(@"点击名片");
        UIWebView * callWebview = [[UIWebView alloc]init];
        [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",dict[@"mobile"]]]]];
        [[UIApplication sharedApplication].keyWindow addSubview:callWebview];
    } else if (model.bodyType == EMMessageBodyTypeText &&
        ([dict[@"recommendType"] integerValue] == 1 || [dict[@"recommendType"] integerValue] == 2 || [dict[@"recommendType"] integerValue] == 4 || [dict[@"recommendType"] integerValue] == 5)) {
        // 点击推荐
        NSLog(@"点击推荐");
    } else {
        [super messageCellSelected:model];
    }
}

#pragma mark - 底部更多按钮的点击事件
/// 选择照片
- (void)moreViewAudioCallAction:(EaseChatBarMoreView *)moreView {
    
//    [super moreViewAudioCallAction:moreView];
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
    // Pop image picker
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
    self.imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
    
    self.isViewDidAppear = NO;
    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
}

/// 拍照
- (void)moreViewLocationAction:(EaseChatBarMoreView *)moreView {
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
#if TARGET_IPHONE_SIMULATOR
    [self showHint:@"模拟器不支持拍照"];
#elif TARGET_OS_IPHONE
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    self.imagePicker.mediaTypes = @[(NSString *)kUTTypeImage,(NSString *)kUTTypeMovie];
    self.imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:self.imagePicker animated:YES completion:NULL];
    
    self.isViewDidAppear = NO;
    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
#endif

}

/// 名片 推荐
- (void)moreView:(EaseChatBarMoreView *)moreView didItemInMoreViewAtIndex:(NSInteger)index {
    
    [self.chatToolbar endEditing:YES];
    
    if (index == 2) { // 名片
        [self sendTextMessage:@"[名片]" withExt:@{
                                                @"recommendType":@3,
                                                @"name":self.personInfo.name,
                                                @"mobile":self.personInfo.mobile
                                                }];
    } else { // 推荐
        
        SISSMessageRecommendViewController *recommendVC = [[SISSMessageRecommendViewController alloc] init];
        recommendVC.recommendHouseBlock = ^(SISSHouseResourceModel *houseModel) {
            
            [self sendTextMessage:@"[推荐]" withExt:@{
                                                    @"recommendType":@1,
                                                    @"id":houseModel.ID,
                                                    @"neighbourhood":houseModel.neighbourhood,
                                                    @"price":houseModel.price,
                                                    @"region":houseModel.region,
                                                    @"regionDetail":houseModel.regionDetail,
                                                    @"area":houseModel.area,
                                                    @"houseType":houseModel.houseType}];
        };
        
        recommendVC.recommendPassengerBlock = ^(SISSPassengerResourceModel *passengerModel) {
            
            [self sendTextMessage:@"[推荐]" withExt:@{
                                                    @"recommendType":@2,
                                                    @"id":passengerModel.ID,
                                                    @"name":passengerModel.name,
                                                    @"minPrice":@(passengerModel.minPrice),
                                                    @"maxPrice":@(passengerModel.maxPrice),
                                                    @"region":passengerModel.region,
                                                    @"regionDetail":passengerModel.regionDetail,
                                                    @"houseType":passengerModel.houseType}];
        };
        
        recommendVC.recommendRentOutBlock = ^(SISSRentOutModel *rentOutModel) {
            [self sendTextMessage:@"[推荐]" withExt:@{
                                                    @"recommendType":@4,
                                                    @"id":rentOutModel.ID,
                                                    @"neighbourhood":rentOutModel.neighbourhood,
                                                    @"monthlyRent":rentOutModel.monthlyRent,
                                                    @"region":rentOutModel.region,
                                                    @"regionDetail":rentOutModel.regionDetail,
                                                    @"area":rentOutModel.area,
                                                    @"houseType":rentOutModel.houseType}];
        };
        
        recommendVC.recommendTenantBlock = ^(SISSTenantModel *tenantModel) {
            [self sendTextMessage:@"[推荐]" withExt:@{
                                                    @"recommendType":@5,
                                                    @"id":tenantModel.ID,
                                                    @"renterName":tenantModel.renterName,
                                                    @"minPrice":tenantModel.minPrice,
                                                    @"maxPrice":tenantModel.maxPrice,
                                                    @"region":tenantModel.region,
                                                    @"regionDetail":tenantModel.regionDetail,
                                                    @"houseType":tenantModel.houseType}];
        };
        
        SISSNavigationController *nav = [[SISSNavigationController alloc] initWithRootViewController:recommendVC];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:nav animated:YES completion:nil];
//        
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//        
//        UIAlertAction *houseAlert = [UIAlertAction actionWithTitle:@"房源推荐" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [self sendTextMessage:@"[推荐]" withExt:@{
//                                                    @"recommendType":@1,
//                                                    @"neighbourhood":@"珠光花园",
//                                                    @"price":@500,
//                                                    @"region":@"南山区",
//                                                    @"regionDetail":@"西丽",
//                                                    @"area":@88,
//                                                    @"houseType":@"2房"}];
//            NSLog(@"房源推荐");
//        }];
//        
//        UIAlertAction *passengerAlert = [UIAlertAction actionWithTitle:@"客源推荐" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            [self sendTextMessage:@"[推荐]" withExt:@{
//                                                    @"recommendType":@2,
//                                                    @"name":@"张三",
//                                                    @"minPrice":@300,
//                                                    @"maxPrice":@500,
//                                                    @"region":@"南山区",
//                                                    @"regionDetail":@"西丽",
//                                                    @"houseType":@"2房"}];
//            NSLog(@"客源推荐");
//        }];
//        
//        [alertController addAction:houseAlert];
//        [alertController addAction:passengerAlert];
//        
//        [self presentViewController:alertController animated:YES completion:nil];
    }
    
}

// 收到消息回调
//- (void)messagesDidReceive:(NSArray *)aMessages {
//    [super messagesDidReceive:aMessages];
//    
//    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
//    // 2.1 系统声音
//    AudioServicesPlaySystemSound(1007);
////    for (EMMessage *message in aMessages) {
////        NSLog(@" -- %@",message.body);
////        // 消息中的扩展属性
////        NSDictionary *ext = message.ext;
////        
////        NSLog(@"消息中的扩展属性是 -- %@",ext);
////        
////        // 调用震动代码
////        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
////        // 2.1 系统声音
////        AudioServicesPlaySystemSound(1007);
////        
////        /*
////        // 2.2 用户音效
////        //音效文件路径
////        NSString *path = [[NSBundle mainBundle] pathForResource:@"message" ofType:@"wav"];
////        //组装并播放音效
////        SystemSoundID soundID;
////        NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
////        AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
////        AudioServicesPlaySystemSound(soundID);
////        //声音停止
////        AudioServicesDisposeSystemSoundID(soundID);
////         */
////        /*
////         {
////         region = 罗湖区;
////         regionDetail = 黄贝;
////         id = 3429976522195968;
////         recommendType = 2;
////         houseType = 三房;
////         maxPrice = 90.0;
////         name = 曾维俊;
////         minPrice = 50.0;
////         }
////         */
////    }
//}



/**
 获取个人信息
 */
- (void)requestPeronInfo {
    
    [SISSPublicSingleton shared].isHud = YES;
    [kNetworkManager requestPersonInfoWithSpId:[SISSUserAccount shared].spId success:^(SISSPersonInfoModel *personInfo) {
        
        self.personInfo = personInfo;
        
    } failed:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}

@end
